package org.kent.w.base.common.validate;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Hibernate Validator
 *
 * @author wujigang
 * @date 2019/9/17
 */
public class HibernateValidateHelper {

    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class).configure()
                .failFast(true)
                .buildValidatorFactory();
        validator = factory.getValidator();
    }

    public static ValidateResult validate(Object obj) {
        if (null == obj) {
            throw new IllegalArgumentException("obj is null");
        }

        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);

        if (null == constraintViolations || constraintViolations.size() == 0) {
            return ValidateResult.builder().success(true).build();
        }

        ValidateResult result = ValidateResult.builder().success(false).build();

        for (ConstraintViolation constraintViolation : constraintViolations) {
            result.addMessage(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
        }

        return result;
    }
}
